import { http } from "@/utils/http";

// 后台管理用户详情相关类型定义

export interface UserBasicInfo {
  userId: number;
  userName: string;
  nickName: string;
  email: string;
  phonenumber: string;
  avatar?: string;
  sex: string;
  sexName: string;
  status: number;
  statusName: string;
  createTime: string;
  updateTime: string;
  createBy: string;
  updateBy: string;
  roleNames: string[];
}

export interface UserStats {
  articleCount: number;
  draftCount: number;
  deletedCount: number;
  totalViewCount: number;
  totalLikeCount: number;
  totalCommentCount: number;
  totalCollectCount: number;
  followerCount: number;
  followingCount: number;
  receivedLikeCount: number;
  givenLikeCount: number;
  commentGivenCount: number;
  commentReceivedCount: number;
}

export interface CategoryStat {
  categoryName: string;
  articleCount: number;
  totalViews: number;
  totalLikes: number;
}

export interface UserContentInfo {
  firstPublishTime: string;
  lastPublishTime: string;
  avgViewsPerArticle: number;
  avgLikesPerArticle: number;
  categoryStats: CategoryStat[];
  topTags: string[];
  publishFrequency: number;
}

export interface UserInteractionInfo {
  lastLoginTime: string;
  lastActiveTime: string;
  loginDays: number;
  avgDailyActiveTime: number;
  totalSessions: number;
  activeTimeRanges: string[];
}

export interface UserSecurityInfo {
  lastLoginIp: string;
  lastLoginLocation: string;
  lastLoginDevice: string;
  recentLoginIps: string[];
  suspiciousLoginCount: number;
  isEmailVerified: boolean;
  isPhoneVerified: boolean;
  passwordLastChanged: string;
}

export interface UserActivity {
  activityType: string;
  activityDescription: string;
  activityTime: string;
  ipAddress: string;
  userAgent: string;
  result: string;
}

export interface AdminUserProfile {
  basicInfo: UserBasicInfo;
  stats: UserStats;
  contentInfo: UserContentInfo;
  interactionInfo: UserInteractionInfo;
  securityInfo: UserSecurityInfo;
  recentActivities: UserActivity[];
}

export interface ContentStatsParams {
  userId: number;
  days?: number;
}

export interface ActivityStatsParams {
  userId: number;
  days?: number;
}

export interface CleanExpiredActivitiesParams {
  days?: number;
}

// 用户活动记录管理相关类型定义

export interface UserActivityQuery {
  userId?: number;
  activityTypes?: string[];
  typeGroup?: string;
  result?: string;
  ipAddress?: string;
  timeRange?: string;
  keyword?: string;
  targetType?: string;
  targetId?: number;
  importantOnly?: boolean;
  orderBy?: string;
  orderDirection?: string;
  page?: number;
  size?: number;
}

export interface UserActivityRecord {
  activityType: string;
  activityDescription: string;
  activityTime: string;
  ipAddress: string;
  userAgent: string;
  result: string;
  targetType?: string;
  targetId?: number;
  userId?: number;
  userName?: string;
  nickName?: string;
}

export interface UserActivityPageResult {
  records: UserActivityRecord[];
  total: number;
  current: number;
  size: number;
}

export interface ActivityStatistics {
  totalActivities: number;
  successActivities: number;
  failedActivities: number;
  successRate: number;
}

export interface ActivityTypeGroup {
  name: string;
  types?: string[];
  description?: string;
}

export interface ActivityTypeGroups {
  [key: string]: ActivityTypeGroup;
}

export interface TimeRangeOptions {
  [key: string]: string;
}

// API接口函数

/**
 * 获取后台管理用户详情信息
 */
export const getAdminUserProfileApi = (userId: number) => {
  return http.request<any>("get", `/admin/user-profile/${userId}`);
};

/**
 * 获取用户内容发布统计
 */
export const getUserContentStatsApi = (params: ContentStatsParams) => {
  const { userId, ...queryParams } = params;
  return http.request<any>(
    "get",
    `/admin/user-profile/${userId}/content-stats`,
    {
      params: queryParams
    }
  );
};

/**
 * 获取用户活动统计
 */
export const getUserActivityStatsApi = (params: ActivityStatsParams) => {
  const { userId, ...queryParams } = params;
  return http.request<any>(
    "get",
    `/admin/user-profile/${userId}/activity-stats`,
    {
      params: queryParams
    }
  );
};

/**
 * 重新计算用户统计数据
 */
export const recalculateUserStatsApi = (userId: number) => {
  return http.request<any>(
    "post",
    `/admin/user-profile/${userId}/recalculate-stats`
  );
};

/**
 * 清理过期活动记录
 */
export const cleanExpiredActivitiesApi = (
  params?: CleanExpiredActivitiesParams
) => {
  return http.request<null>(
    "post",
    "/admin/user-profile/clean-expired-activities",
    {
      data: params
    }
  );
};

// 用户活动记录管理API接口

/**
 * 分页查询用户活动记录
 */
export const getUserActivityListApi = (params: UserActivityQuery) => {
  return http.request<UserActivityPageResult>(
    "get",
    "/admin/user-activity/list",
    {
      params
    }
  );
};

/**
 * 获取用户最近活动记录
 */
export const getUserRecentActivitiesApi = (userId: number, limit?: number) => {
  return http.request<any>("get", `/admin/user-activity/recent/${userId}`, {
    params: { limit }
  });
};

/**
 * 获取活动统计信息
 */
export const getActivityStatisticsApi = (userId?: number, days?: number) => {
  return http.request<ActivityStatistics>(
    "get",
    "/admin/user-activity/statistics",
    {
      params: { userId, days }
    }
  );
};

/**
 * 获取活动类型分组信息
 */
export const getActivityTypeGroupsApi = () => {
  return http.request<ActivityTypeGroups>(
    "get",
    "/admin/user-activity/type-groups"
  );
};

/**
 * 获取时间范围选项
 */
export const getTimeRangeOptionsApi = () => {
  return http.request<TimeRangeOptions>(
    "get",
    "/admin/user-activity/time-ranges"
  );
};

/**
 * 清理过期活动记录（新接口）
 */
export const cleanExpiredUserActivitiesApi = () => {
  return http.request<string>("post", "/admin/user-activity/clean-expired");
};

// 工具函数

/**
 * 格式化数字显示（如：1000 -> 1k）
 */
export const formatNumber = (num: number): string => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + "M";
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + "k";
  }
  return num.toString();
};

/**
 * 格式化时间显示
 */
export const formatTime = (timeStr: string): string => {
  const time = new Date(timeStr);
  const now = new Date();
  const diff = now.getTime() - time.getTime();

  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;
  const month = 30 * day;
  const year = 365 * day;

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    return Math.floor(diff / minute) + "分钟前";
  } else if (diff < day) {
    return Math.floor(diff / hour) + "小时前";
  } else if (diff < month) {
    return Math.floor(diff / day) + "天前";
  } else if (diff < year) {
    return Math.floor(diff / month) + "个月前";
  } else {
    return Math.floor(diff / year) + "年前";
  }
};

/**
 * 获取用户状态类型（用于标签颜色）
 */
export const getUserStatusType = (status?: number) => {
  const typeMap: Record<number, any> = {
    0: "danger", // 禁用
    1: "success" // 启用
  };
  return typeMap[status || 0] || "info";
};

/**
 * 获取活动类型图标
 */
export const getActivityIcon = (activityType: string): string => {
  const iconMap: Record<string, string> = {
    LOGIN: "ep:user",
    LOGOUT: "ep:switch-button",
    PUBLISH: "ep:edit",
    COMMENT: "ep:chat-line-round",
    LIKE: "ep:star",
    FOLLOW: "ep:plus",
    UNFOLLOW: "ep:minus"
  };
  return iconMap[activityType] || "ep:operation";
};

/**
 * 获取活动结果类型
 */
export const getActivityResultType = (result: string) => {
  const typeMap: Record<string, any> = {
    SUCCESS: "success",
    FAILED: "danger",
    WARNING: "warning"
  };
  return typeMap[result] || "info";
};

/**
 * 格式化IP地址显示
 */
export const formatIpAddress = (ip: string): string => {
  if (!ip) return "未知";
  // 简单的IP地址脱敏处理
  const parts = ip.split(".");
  if (parts.length === 4) {
    return `${parts[0]}.${parts[1]}.***.**`;
  }
  return ip;
};

/**
 * 计算活跃度等级
 */
export const getActivityLevel = (
  avgDailyActiveTime: number
): { level: string; color: string; text: string } => {
  if (avgDailyActiveTime >= 180) {
    return { level: "high", color: "#67c23a", text: "高活跃" };
  } else if (avgDailyActiveTime >= 60) {
    return { level: "medium", color: "#e6a23c", text: "中活跃" };
  } else if (avgDailyActiveTime >= 30) {
    return { level: "low", color: "#f56c6c", text: "低活跃" };
  } else {
    return { level: "inactive", color: "#909399", text: "不活跃" };
  }
};

/**
 * 获取活动类型分组名称
 */
export const getActivityTypeGroupName = (typeGroup: string): string => {
  const groupMap: Record<string, string> = {
    AUTH: "认证相关",
    MANAGEMENT: "管理操作",
    CONTENT: "内容管理",
    SOCIAL: "社交互动",
    IMPORTANT: "重要操作"
  };
  return groupMap[typeGroup] || typeGroup;
};

/**
 * 获取时间范围名称
 */
export const getTimeRangeName = (timeRange: string): string => {
  const rangeMap: Record<string, string> = {
    TODAY: "今天",
    YESTERDAY: "昨天",
    LAST_7_DAYS: "最近7天",
    LAST_30_DAYS: "最近30天",
    LAST_90_DAYS: "最近90天"
  };
  return rangeMap[timeRange] || timeRange;
};

/**
 * 获取活动类型中文名称
 */
export const getActivityTypeDisplayName = (activityType: string): string => {
  const typeMap: Record<string, string> = {
    LOGIN: "登录",
    LOGOUT: "登出",
    LOGIN_FAILED: "登录失败",
    PASSWORD_CHANGED: "密码修改",
    USER_CREATED: "创建用户",
    USER_UPDATED: "更新用户",
    USER_DELETED: "删除用户",
    USER_STATUS_CHANGED: "用户状态变更",
    USER_ROLE_ASSIGNED: "分配角色",
    ROLE_CREATED: "创建角色",
    PERMISSION_ASSIGNED: "分配权限",
    ARTICLE_PUBLISHED: "发布文章",
    ARTICLE_UPDATED: "更新文章",
    ARTICLE_DELETED: "删除文章",
    ARTICLE_STATUS_CHANGED: "文章状态变更",
    USER_FOLLOWED: "关注用户",
    ARTICLE_LIKED: "点赞文章",
    COMMENT_POSTED: "发表评论",
    FILE_UPLOADED: "文件上传",
    FILE_DELETED: "文件删除",
    SYSTEM_CONFIG_CHANGED: "系统配置变更",
    DATA_EXPORT: "数据导出",
    SECURITY_VIOLATION: "安全违规"
  };
  return typeMap[activityType] || activityType;
};

/**
 * 判断是否为重要操作
 */
export const isImportantActivity = (activityType: string): boolean => {
  const importantTypes = [
    "LOGIN_FAILED",
    "PASSWORD_CHANGED",
    "USER_CREATED",
    "USER_UPDATED",
    "USER_DELETED",
    "USER_STATUS_CHANGED",
    "USER_ROLE_ASSIGNED",
    "ROLE_CREATED",
    "PERMISSION_ASSIGNED",
    "ARTICLE_DELETED",
    "ARTICLE_STATUS_CHANGED",
    "SYSTEM_CONFIG_CHANGED",
    "DATA_EXPORT",
    "SECURITY_VIOLATION"
  ];
  return importantTypes.includes(activityType);
};

/**
 * 获取操作风险等级
 */
export const getActivityRiskLevel = (
  activityType: string,
  result: string
): { level: string; color: string; text: string } => {
  if (result === "FAILED") {
    return { level: "high", color: "#f56c6c", text: "高风险" };
  }

  if (activityType === "SECURITY_VIOLATION") {
    return { level: "high", color: "#f56c6c", text: "高风险" };
  }

  if (isImportantActivity(activityType)) {
    return { level: "medium", color: "#e6a23c", text: "中风险" };
  }

  return { level: "low", color: "#67c23a", text: "低风险" };
};
